var pomelo = require('pomelo');
var jwt = require('jsonwebtoken');

var dataManager = require('../../../services/dataManager');
var utils = require('../../../util/utils');

var log = console.log;

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
    // init data manager
    // DataManager.initDataFromFile();
};

var handler = Handler.prototype;
var gameServerConf = {
    1: { // 百家乐
        type: 'bjl',
        file: 'gameRemote',
        enter: 'enterGame',
        kick: 'kick'
    },
    2: { // 百人牛牛
        type: 'niuniu',
        file: 'gameRemote',
        enter: 'enterGame',
        kick: 'kick'
    },
    3: { // 疯狂赛车
        type: 'fksc',
        file: 'gameRemote',
        enter: 'enterGame',
        kick: 'kick'
    },
    4: { // 温州两张
        type: 'wzlz',
        file: 'gameRemote',
        enter: 'enterGame',
        kick: 'kick'
    },
    5: { // 二人牛牛
        type: 'ernn',
        file: 'gameRemote',
        enter: 'enterGame',
        kick: 'kick'
    }
};

// enter game
// msg: {playerId, token, gameId}

/**
 * 进入游戏
 * connector.handler.enterGame
 * in: {playerId, token, gameId}
 * out: {
 *      gameId,
 *      roomId,
 *      playerData: {name, coin, score, roundCount},
 *      playerList: [{playerId, name, coin}, ...],
 *      bankerData: {bankerId, bankerRound, bankerScore},
 *      bankerList: [playerId, ...],
 *      roomSet: { bankerMinCoin }
 * }
 */
handler.enterGame = function (msg, session, next) {
    msg.serverId = this.app.get('serverId');
    var self = this;
    var sessionService = self.app.get('sessionService');

    // log('连接到 connector 服务器！');
    // log(msg);

    // log(session.__session__.__socket__.socket.upgradeReq.headers);

/* cSpell:disable */
    // console.log('解析token');
    // msg.playerId = jwt.verify(msg.token, '34t9gijkedrgp94wi3tkje4').sub;
    // console.log('解析成功：msg.playerId = ', msg.playerId);
/* cSpell:enable */

    var playerId,
        err = checkLoginData(msg);

    // 首先检查用户数据是否正常
    if (err) {
        next(null, { err });
        return;
    }

    playerId = msg.playerId;

    // 然后检查用户在线状态及账号状态
    dataManager.checkPlayer(msg, function (err) {

        if (err) {
            next(null, { err });
            return;
        }

        // 如果已经登录了,踢掉之前登录的所有session
        if (sessionService.getByUid(playerId)) {
            console.log('old player kick');
            sessionService.kick(playerId, 'have login in another place!', function () {
                console.log('kickCb');
            });
        }

        session.bind(playerId);
        session.set('playerId', playerId);
        session.set('serverId', msg.serverId);

        // msg.playerName = '玩家' + msg.playerId;
        msg.isRobot = false;

        // enter game
        // 这里应该根据msg.gameId 进入不同的游戏

        msg.ip = utils.getIPFromSession(session);

        // log(session.__session__.__socket__.remoteAddress);
        // log(sessionService.getClientAddressBySessionId(session.id));

        var serverConf = gameServerConf[msg.gameId];
        var type = serverConf.type,
            file = serverConf.file,
            func = serverConf.enter;

        self.app.rpc[type][file][func](session, msg, function (err, data) {
            if (err) {
                console.log('entryHandler err: ', err);

                next(null, { err: err.toString() });

                sessionService.kick(playerId, function () {
                    console.log(playerId + '：未能成功进入游戏');
                });
                return;
            }

            if (data.gameId && data.gameId > 0) {
                session.set('gameId', data.gameId);
            }

            if (data.roomId) {
                session.set('roomId', data.roomId);
            }

            console.log('进入游戏成功！返回前台数据：', data);

            // 后移 session 绑定时间，确认登录成功才绑定下线事件
            session.on('closed', onPlayerLeave.bind(null, self.app));

            session.pushAll();
            // 把 session 的改变从 backendSession push到 front Session
            next(null, data);
        });
    });

};

function checkLoginData(msg) {
    log('检查登录数据');

    var playerId = parseInt(msg.playerId);
    var err;

    // 首先检查用户id是否正常，以及是否已经登录此游戏
    if (!playerId || (playerId <= 0)) {
        err = 'player: Id:' + playerId + ' error!';
    }

    if (!msg.gameId) {
        err = 'gameId not exist!';
    }

    if (!gameServerConf[msg.gameId]) {
        err = 'gameId not match!';
    }

    if (!msg.token) {
        err = 'token not exist!';
    }

    return err;
}


/**
 * User log out handler
 *
 * @param {Object} app current application
 * @param {Object} session current session object
 *
 */
// 不管在session.on('event', cb)的cb中传入了多少参数，session都是最后一个参数
var onPlayerLeave = function (app, session) {

    console.log('用户离开 entryHandler.js onPlayerLeave .......................');

    var sessionService = app.get('sessionService');

    // log(sessionService.service.uidMap);

    if (!session || !session.uid) {
        console.log('return;');
        return;
    }

    var gameId = session.get('gameId'),
        roomId = session.get('roomId'),
        playerId = session.get('playerId'),
        serverId = session.get('serverId');

    // connectorServerId可以在最开始的时候就获取到，然后向后面的服务传递
    var data = {
        gameId,
        roomId,
        playerId,
        serverId
    };

    log('data: ', data);

    var serverConf = gameServerConf[gameId];

    if (!serverConf) {
        return;
    }
    var type = serverConf.type, file = serverConf.file, func = serverConf.kick;

    app.rpc[type][file][func](session, data, function() {
        console.log('caught kickPlayer callback.................');
        console.warn('玩家 ' + data.playerId + ' 的连接断开了！');
    });

};

